/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action.retail;

import cart.ShoppingCart;
import cart.ShoppingCartItem;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import database.ProductDAO;
import java.util.List;
import java.util.Map;
import model.Product;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

/**
 *
 * @author Thai Ha Cong
 */
@Namespace("/")
public class AddToCartAction extends ActionSupport {
    
    private int productId;
    private int productQuantity;
    
    public AddToCartAction() {
    }
    
    public int getProductId() {
        return productId;
    }
    
    public void setProductId(int productId) {
        this.productId = productId;
    }
    
    public int getProductQuantity() {
        return productQuantity;
    }

//    @RequiredStringValidator(message = "Product Quantity is required.")
//    @RegexFieldValidator(message = "Invalid Product Quantity.", key = "phone.invalid", expression = "\\d{1}")
    public void setProductQuantity(int productQuantity) {
        this.productQuantity = productQuantity;
    }
    
    @Action(value = "addToCart", results = {
        @Result(name = "success", location = "/redirect/rdrViewShoppingCart.jsp")
    })
    @Override
    public String execute() throws Exception {

//        HttpServletRequest request = ServletActionContext.getRequest();
//        
//        int quantity;
//        try {
//            quantity = Integer.parseInt(request.getParameter("productQuantity"));
//        } catch (Exception e) {
//            quantity = 1;
//        }
        
        if (productQuantity < 1 || productQuantity > 5) {
            productQuantity = 1;
        }
        
        Map session = ActionContext.getContext().getSession();
        
        ProductDAO productDAO = new ProductDAO();
        
        Product product = productDAO.getProductFromProductId(productId);
        
        double price = product.getUnitPrice() - product.getSale();
        
        ShoppingCart sc = (ShoppingCart) session.get("shoppingCart");
        if (sc == null) {
            sc = new ShoppingCart();
        }
        sc.addItem(new ShoppingCartItem(productQuantity, price, product));
        
        List<ShoppingCartItem> shoppingCartItemList = sc.getShoppingCartItemList();
        ShoppingCartItem sci = shoppingCartItemList.get(shoppingCartItemList.indexOf(new ShoppingCartItem(product)));
        if (sci.getQuantity() > 5) {
            sci.setQuantity(5);
            //addActionMessage("Quantity is Limited by 5 per Customer.");
        }
        
        session.put("shoppingCart", sc);
        
        return SUCCESS;
    }
}